jQuery(document).ready(function($) {
	
	var id= 	new Array();
	var value= 	new Array();
		
try {
	$('.slider').each(function(index) {

		value[index] = $(this).next("input").val();
		
		id[index] = $(this).attr('id');				
	});
		
		

	for (var i=0; i < id.length; i++) {
		$("#"+id[i]).slider({
			value:value[i], 
			slide:refreshSwatch, 
			max:100})
	};
		
	$('.dealer input').blur(function() {
		refreshSwatch()
	});
	
	$('.zero_set a').unbind('click');
	$('.zero_set a').bind('click',function(){
		$(this).parent().parent().find('.slider').slider('value','0');
		$(this).parent().parent().find('.slider').addClass("modified").next('input').val(0);
	         calculateTotal();	
                                         });
		$(':submit').css('cursor','pointer');

	calculateTotal();

} catch (err) {
	//if(window.console) { window.console.log(err) }	
	return false;
}
	
		
});

function refreshSwatch() {
	$(this).addClass("modified").next('input').val($(this).slider('value') )
	calculateTotal();
}

function calculateTotal () {
	var total = 0;
	var inp= 	new Array();
	$('.dealer input').each(function(index) {
		inp[index] = parseInt($(this).val())
		total = inp[index]+total;
	});
	$('#total').text(total)
	if (total == 100) {
		$('#total').addClass('success');
		$(':submit').val('submit');
		$(':submit').unbind('click');	
		$(':submit').bind('click',function (){
	        });	
	} else {
		$('#total').removeClass('success');
		$(':submit').val('normalize');
		$(':submit').unbind('click');	
		$(':submit').bind('click',function (){
			normalize();
  		   return false;
	        });	
		
		
	}
/* brings everything to nice 100 sum */

function normalize (){
	c = 0; /* current bad total */
	d = 0; /* awesome new total */
	newvalue = 0; /* correction */
	firstseen=0; /* value of first one to be tagged for later compensation */
	$('.slider').each(function(index) {
		c = c + parseInt($(this).next("input").val());
	});
	$('.slider').each(function(index) {
		if($(this).next("input").val() > 0){  /* don't mess with zeros */
			newvalue= Math.round($(this).next("input").val()/c*100); 
			d = d  + parseInt(newvalue);
        	        $(this).next("input").val( newvalue);
			$(this).slider('value',newvalue);
			if(firstseen<0.1){
				$(this).addClass('compensator');
				firstseen=newvalue;
                        }
		}
	});
	/* since there's not a great chance that the rounding will work out perfect 
	* unjustly bless/curse the first non-zero dealer with the adjustment */
        $('.compensator').next("input").val( firstseen + ( 100 - d ) );
	$('.compensator').slider('value', firstseen + ( 100 - d )); 
	calculateTotal();
		
}
	
}
